<?php

namespace App\Console\Commands;

use Aliyun\AliSms;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\User\StoreController;
use App\Api\Controllers\Vbill\BaseController;
use App\Models\SmsConfig;
use App\Models\StorePayWay;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VbillSyncRate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vbill_sync_rate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Synchronous rate operation';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        try {
            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("vbill_sync_rates");
            } else {
                $obj = DB::table('vbill_sync_rates');
            }

            $start_time = date('Y-m-d 00:00:00', strtotime("-1 day"));
            $end_time = date('Y-m-d 23:59:59', strtotime("-1 day"));

            $vbillSyncRatesObjArrs = $obj->where('act_status', 0)
                ->where('created_at', '>=', $start_time)
                ->where('created_at', '<=', $end_time)
                ->get()
                ->toArray();

            foreach ($vbillSyncRatesObjArrs as $vbillSyncRatesObj) {
                $config_id = $vbillSyncRatesObj->config_id;
                $store_id = $vbillSyncRatesObj->store_id;
                $vbill_config_obj = new VbillConfigController();
                if ($vbillSyncRatesObj->ori_type == 1) { //1-vbill;2-vbilla
                    $vbillConfigObj = $vbill_config_obj->vbill_config($config_id);
                    $vbillStoreObj = $vbill_config_obj->vbill_merchant($store_id, 0);
                    $company = 'vbill';
                }
                elseif ($vbillSyncRatesObj->ori_type == 2) { //1-vbill;2-vbilla
                    $vbillConfigObj = $vbill_config_obj->vbilla_config($config_id);
                    $vbillStoreObj = $vbill_config_obj->vbilla_merchant($store_id, 0);
                    $company = 'vbilla';
                } else {
                    Log::info('随行付-同步费率-定时任务-类型异常-error');
                    Log::info($vbillSyncRatesObj);
                    continue;
                }

                if (!$vbillConfigObj || !$vbillConfigObj->orgId || !$vbillConfigObj->privateKey || !$vbillConfigObj->sxfpublic) {
                    continue;
                }
                if (!$vbillStoreObj || !$vbillStoreObj->mno) {
                    continue;
                }
                $orgId = $vbillConfigObj->orgId;
                $private_key = $vbillConfigObj->privateKey;
                $public_key = $vbillConfigObj->sxfpublic;
                $mno = $vbillStoreObj->mno;

                //商户信息查询接口
                $vbillObj = new BaseController();
                $url = $vbillObj->store_query_info; //查询本机构下的商户详细信息
                $store_query_info_data = [
                    'orgId' => $orgId,
                    'reqId' => time(),
                    'version' => '1.0',
                    'timestamp' => date('Ymdhis', time()),
                    'signType' => 'RSA',
                    'reqData' => [
                        'mno' => $mno
                    ]
                ];

                $store_query_info_res = $vbillObj->execute($store_query_info_data, $url, $private_key, $public_key);
                Log::info('随行付-同步费率-定时任务-商户信息查询');
                Log::info($store_query_info_res);
                if ($store_query_info_res['data']['code'] == "0000" && $store_query_info_res['data']['respData']['bizCode'] != "0000") {
                    Log::info('随行付-同步费率-定时任务-返回-error');
                    Log::info($vbillSyncRatesObj);
                    continue;
                }

                //系统错误
                if ($store_query_info_res['status'] == 0) {
                    continue;
                }

                //业务成功
                if ($store_query_info_res['data']['code'] == "0000") {
                    $vbill_now_rate = isset($store_query_info_res['data']['respData']['qrcodeList'][0]['rate']) ? $store_query_info_res['data']['respData']['qrcodeList'][0]['rate']: 0;
                    if (!$vbill_now_rate) {
                        continue;
                    }

                    $StorePayWayObjArrs = StorePayWay::where('store_id', $store_id)
                        ->where('company', $company)
                        ->get()
                        ->toArray();
                    foreach ($StorePayWayObjArrs as $StorePayWayArr) {
//                        Log::info('随行付-同步费率-定时任务-旧费率');
//                        Log::info($StorePayWayArr);
                        //费率一致不更新门店费率
                        $rate = $StorePayWayArr['rate'];
                        if ($vbill_now_rate != $rate) {
                            $update_rate_res = StorePayWay::where('store_id', $store_id)
                                ->where('company', $company)
                                ->update([
                                    'rate' => $vbill_now_rate
                                ]);
                            if (!$update_rate_res) {
                                Log::info('随行付-同步费率-定时任务-更新费率失败22-error');
                                Log::info('store_id: '. $store_id);
                                Log::info('company: '. $company);
                                Log::info('rate: '. $rate);
                                Log::info('vbill_now_rate: '. $vbill_now_rate);
                                //TODO:发送短信通知
                            } else {
                                //更新操作表
                                $vbillSyncRatesObjRes = $obj->where('store_id', $store_id)
                                    ->where('ori_type', $vbillSyncRatesObj->ori_type)
                                    ->where('created_at', '>=', $start_time)
                                    ->where('created_at', '<=', $end_time)
                                    ->update([
                                        'new_rate' => $vbill_now_rate,
                                        'act_status' => 1,
                                        'updated_at' => date('Y-m-d H:i:s', time())
                                    ]);
                                if (!$vbillSyncRatesObjRes) {
                                    Log::info('随行付-同步费率-定时任务-更新操作表失败22-error');
                                    Log::info('store_id: '. $store_id);
                                    Log::info('company: '. $company);
                                    Log::info('vbill_now_rate: '. $vbill_now_rate);
                                }
                            }
                        }
                    }
                }

            }

        } catch (\Exception $ex) {
            Log::info('随行付-次日同步费率-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

    }


    public function send($name, $status, $phone, $config_id = '1234')
    {
        try {
            $config = SmsConfig::where('type', '7')->where('config_id', $config_id)->first();
            if (!$config) {
                $config = SmsConfig::where('type', '7')->where('config_id', '1234')->first();
            }

            if ($config && $config->app_key && $phone) {
                $data = ["name" => $name, 'status' => $status];
                $this->sendSms($phone, $config->app_key, $config->app_secret, $config->SignName, $config->TemplateCode, $data);
            }
        } catch (\Exception $ex) {
            Log::info('随行付-次日同步费率-发送短信-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    public function sendSms($phone, $app_key, $app_secret, $SignName, $TemplateCode, $data)
    {
        $demo = new AliSms($app_key, $app_secret);
        $response = $demo->sendSms(
            $SignName, // 短信签名
            $TemplateCode, // 短信模板编号
            $phone, // 短信接收者
            $data
        );

        return $response;
    }


}
